package com.shenrongrong.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.shenrongrong.common.Result;
import com.shenrongrong.model.User;
import com.shenrongrong.service.UserService;
import com.shenrongrong.utils.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public Result selectUser(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "5") Integer pageSize,
                             User user) {
        System.out.println("selectUser");
        PageInfo<User> pageInfo= userService.selectUser(pageNum, pageSize, user);
        return Result.success(pageInfo);
    }

    @PutMapping("/updateUsername")
    public Result updateUsername(@RequestBody User user) {
        System.out.println("updateUsername");
        boolean isUsernameExists = userService.isUsernameUnique(user.getUsername());
        if(!isUsernameExists)
        {
            int updateList = userService.updateUser(user);
            return Result.success(updateList);
        }
        return Result.error("该用户名已存在");
    }
    @PutMapping("/updateUser")
    public Result updateAvatar(@RequestBody User user) {
        System.out.println("updateUser");
        int updateList = userService.updateUser(user);
        return Result.success(updateList);
    }

    @DeleteMapping("/deleteUser/{userid}")
    public Result deleteUser(@PathVariable Integer userid) {
        System.out.println("deleteUser");
        int deleteList = userService.deleteUser(userid);
        return Result.success(deleteList);
    }

    @PostMapping("/insertUser")
    public Result insertUser(@RequestBody User user) {
        System.out.println("insertUser");
        boolean isPhoneExists = userService.isPhoneUnique(user.getPhone());
        boolean isUsernameExists = userService.isUsernameUnique(user.getUsername());
        if (isPhoneExists) {
            return Result.error("电话已被注册");  // 明确返回失败原因
        }
        if (isUsernameExists) {
            return Result.error("用户名已被注册");
        }
        userService.insertUser(user);
        return Result.success("注册成功");

    }

    @PostMapping("/loginUser")
    public Result loginUser(@RequestBody User user) {
        System.out.println("loginUser");
        boolean isUserExists = userService.isUserUnique(user.getUsername(), user.getPassword(),user.getRole());
        if (isUserExists) {
            User loginUser = userService.selectUser(user).getFirst();
//            用户存在，创建用户token
            Map<String, String> userClaims = new HashMap<>();
//            userClaims.put("userId", loginUser.getUserid().toString());
            userClaims.put("role", loginUser.getRole().toString());
            String token = JwtUtil.generateToken(loginUser.getUserid().toString(), userClaims);
//            设置token
            loginUser.setToken(token);
            return Result.success(loginUser);
        }
        return Result.error("用户不存在或密码错误");
    }


    @GetMapping("/export")
    public void exportExcel(User user, HttpServletResponse response) throws IOException {
        //1、根据查询条件拿到所有符合条件的数据
        List<User>  list = userService.selectUser(user);
        //2、构建Writer对象
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //3、设置中文表头
        writer.addHeaderAlias("username","账号");
        writer.addHeaderAlias("password","密码");
        writer.setOnlyAlias(true);// 默认的，未添加alias的属性也会写出，可以调用此方法排除
        //4、写数据到writer
        writer.write(list);
        // 5. 设置输出的文件的名称以及输出流的头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息导出", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        //这行代码专门为跨域设置的，使axios能获取到响应头的Content-Disposition
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        //6、获取输出流，往浏览器写数据
        OutputStream os = response.getOutputStream();
        writer.flush(os);
        writer.close();
        os.close();
    }

    //批量导入
    @PostMapping("/import")
    public Result importExcel(MultipartFile file) throws IOException {
        //1. 拿到输入流，构建reader
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //2. 读取Excel数据，封装到list中
        reader.addHeaderAlias("账号","username");
        reader.addHeaderAlias("电话","phone");
        reader.addHeaderAlias("密码","password");
        reader.addHeaderAlias("角色","role");
        List<User> list = reader.readAll(User.class);
        //3、将数据写入到数据库
        for (User user : list) {
            userService.insertUser(user);
        }
        return  Result.success();
    }
}
